package com.battcn.platform.config.shiro;


import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.session.Session;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Levin
 * @since 2018/11/27 0027
 */
public class ShiroCache implements Cache<Serializable, Session> {

    private long expire = 30 * 60 * 1000;
    private String keyPrefix = "shiro-session:";
    private RedisTemplate<Serializable, Session> redisTemplate;

    public ShiroCache(long expire, String keyPrefix, RedisTemplate<Serializable, Session> redisTemplate) {
        this.expire = expire;
        this.keyPrefix = keyPrefix;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public Session get(Serializable sessionId) throws CacheException {
        final String sessionKey = getSessionKey(sessionId);
        redisTemplate.boundValueOps(sessionKey).expire(expire, TimeUnit.MILLISECONDS);
        return redisTemplate.boundValueOps(sessionKey).get();
    }

    @Override
    public Session put(Serializable sessionId, Session session) throws CacheException {
        final String sessionKey = getSessionKey(sessionId);
        Session old = get(sessionKey);
        redisTemplate.boundValueOps(sessionKey).set(session);
        return old;
    }

    @Override
    public Session remove(Serializable sessionId) throws CacheException {
        final String sessionKey = getSessionKey(sessionId);
        Session old = get(sessionKey);
        redisTemplate.delete(sessionKey);
        return old;
    }

    @Override
    public void clear() throws CacheException {
        redisTemplate.delete(keys());
    }

    @Override
    public int size() {
        return keys().size();
    }

    @Override
    public Set<Serializable> keys() {
        return redisTemplate.keys(getSessionKey("*"));
    }

    @Override
    public Collection<Session> values() {
        Set<Serializable> set = keys();
        List<Session> list = new ArrayList<>();
        for (Serializable sessionId : set) {
            list.add(get(sessionId));
        }
        return list;
    }

    private String getSessionKey(Serializable sessionId) {
        return keyPrefix + sessionId;
    }
}